import type { Plugin } from 'vite';
import * as path from "path";
import * as chokidar from "chokidar";
import { execSync } from "child_process";

export type ApiGenerationPluginParam = {
  jsonFilePath: string;
  moduleDeclarationPath: string;
  outputFilePath: string;
};

const genApiCmd = (root: string, pluginParam: ApiGenerationPluginParam) =>
  `gen_api -i ${path.resolve(root, pluginParam.jsonFilePath)} -m ${path.resolve(root, pluginParam.moduleDeclarationPath)} -n ${path.resolve(root, pluginParam.outputFilePath)}`;

function ApiGenerationPlugin(param: ApiGenerationPluginParam) : Plugin {
  return {
    name: "api-json-watcher",
    configResolved(config: any) {
      const watcher = chokidar.watch(
        path.resolve(config.root, param.jsonFilePath),
      );
      watcher.on("change", (filePath) => {
        const apiJsonPath = path.resolve(config.root, param.jsonFilePath);
        if (filePath === apiJsonPath) {
          try {
            execSync(genApiCmd(config.root, param), {
              stdio: "inherit",
              env: process.env,
            });
            console.log(`${param.outputFilePath} has been updated`);
          } catch (error) {
            console.error("Error executing gen_api command:", error);
          }
        }
      });
    },
  };
}

export { ApiGenerationPlugin };

